Array Element in Memory

Memory Representation of Arrays

Contiguous Allocation

Indexing

Array indexing starts at 0, so the address of the first element arr[0] is the base address of the array.

The address of any element arr[i] can be calculated as:

Address of arr[i] = Base Address + i × Size of Each Element
            

Pointer Representation

The array name (arr) itself acts as a pointer to the first element (&arr[0]).

Example: Storing an Integer Array in Memory


#include  < stdio.h>

int main() {
    int arr[5] = {10, 20, 30, 40, 50}; // Declare and initialize an array

    // Print the addresses and values of each element
    printf("Element\tValue\tAddress\n");
    for (int i = 0; i < 5; i++) {
        printf("arr[%d]\t%d\t%p\n", i, arr[i], (void*)&arr[i]);
    }

    return 0;
}

            

Output:

Element   Value   Address
arr[0]    10      0x7ffee4a2f000
arr[1]    20      0x7ffee4a2f004
arr[2]    30      0x7ffee4a2f008
arr[3]    40      0x7ffee4a2f00c
arr[4]    50      0x7ffee4a2f010
            

Array Address Calculations

For example, if arr[0] is at 0x1000 and sizeof(int) = 4, then:

Pointer Arithmetic in Arrays


#include  < stdio.h>

int main() {
    int arr[5] = {10, 20, 30, 40, 50};

    int *ptr = arr; // Pointer to the first element of the array

    // Access elements using pointer arithmetic
    for (int i = 0; i < 5; i++) {
        printf("Value at ptr + %d: %d (Address: %p)\n", i, *(ptr + i), (void*)(ptr + i));
    }

    return 0;
}

            

Multidimensional Arrays in Memory

In C, multidimensional arrays are stored in contiguous memory locations, in row-major order.


#include < stdio.h>

int main() {
    int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};

    // Print the address of each element
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            printf("arr[%d][%d] = %d (Address: %p)\n", i, j, arr[i][j], (void*)&arr[i][j]);
        }
    }

    return 0;
}

            

Key Points